package com.cgwx.service.impl;

import com.cgwx.Utils.HttpUtil;
import com.cgwx.Utils.RedisUtil;
import com.cgwx.auth.util.TreeUtil.TreeUtils;
import com.cgwx.config.BusinessException;
import com.cgwx.data.dto.*;
import com.cgwx.entity.*;
import com.cgwx.mapper.*;
import com.cgwx.service.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class UtilServiceImpl implements IUtilService {

    @Value("${file_manage.address}")
    private String fileManageAddress;

    @Value("${file_manage.port}")
    private int fileManagePort;

    @Value("${file_manage.url}")
    private String fileManageUrl;

    @Value("${roomSize}")
    private int roomSize;

    @Value("${nonPj}")
    private String nonPj;

    @Resource
    private IFolderService folderService;

    @Resource
    private IFileService fileService;

    @Resource
    private IPersonalRecycleBinService personalRecycleBinService;

    @Resource
    private IRoomService roomService;

    @Resource
    private IAuthorityService authorityService;

    @Resource
    private FolderMapper folderMapper;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private FavoritesMapper favoritesMapper;

    @Resource
    private SharedMapper sharedMapper;

    @Resource
    private IDownloadService downloadService;

    @Resource
    private PersonalRecycleBinMapper personalRecycleBinMapper;

    @Resource
    private MinioFileVersionMapper minioFileVersionMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisUtil redisUtil;

    public static float getFileSize(MultipartFile file) {
        long fileSizeInBytes = file.getSize();
        float f = (float) fileSizeInBytes / (1024 * 1024);
        double temp = f * 1000.0;
        temp = Math.round(temp);
        return (float) (temp / 1000.0);
    }

    @Override
    public String viewFile(String account, String deptId, String entityId, String type) {
        if (type != null && (type.equals("dept") || type.equals("company"))) {
            if (authorityService.checkAuthority(account, deptId, entityId).equals("0")) return "您没有预览权限!";
        }
        File file = new File();
        file.setEntityId(entityId);
        List<File> files = fileService.getFile(file);
        if (files.isEmpty()) return "无该文件!";
        file = files.get(0);
        file.setViewTimes(file.getViewTimes() + 1);
        fileService.updateFileById(file);
        String fileType = file.getType();
        if (fileType != null && (fileType.equals("pdf") || fileType.equals("PDF") || fileType.equals("jpg") || fileType.equals("JPG")
                || fileType.equals("png") || fileType.equals("PNG") || fileType.equals("mp4") || fileType.equals("MP4")
                || fileType.equals("doc") || fileType.equals("DOC") || fileType.equals("docx") || fileType.equals("DOCX")
                || fileType.equals("ofd") || fileType.equals("OFD") || fileType.equals("ppt") || fileType.equals("pptx")
                || fileType.equals("PPT") || fileType.equals("PPTX") || fileType.equals("txt") || fileType.equals("xml")
                || fileType.equals("xls") || fileType.equals("xlsx")))
            return "http://hi.jl1.cn/fileviewtestapi/onlinePreviewSharing?fileId=" + file.getFileId() + "&entityId=" + entityId;
        else return "该格式暂不支持预览!";
    }

    public String upload(MultipartFile multipartFile, String account, float fileSize, String isOuter) {
        String bucketName = "xgb-store";
        String path = "FileSharing";
        String clusterId = account + "/" + getFileLocalDateTime();
        String sysSource = "PermanentAuth";
        if(isOuter != null && isOuter.equals("true")) sysSource = "external";
        String isMultiVersion = "1";
        String url;
        if (fileSize <= 1024) url = fileManageAddress + ":" + fileManagePort + "/file/uploadMultiFileCommon";
        else url = fileManageAddress + ":" + fileManagePort + "/file/uploadMultipartFile2";
        if (multipartFile != null) {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            try {
                HttpPost httpPost = new HttpPost(url);
                MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
                builder.setCharset(StandardCharsets.UTF_8);
                String fileName = multipartFile.getOriginalFilename();
                builder.addBinaryBody("multipartFiles", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
                builder.addTextBody("bucketName", bucketName);
                builder.addTextBody("path", path);
                builder.addTextBody("userId", account);
                builder.addTextBody("clusterId", clusterId);
                builder.addTextBody("sysSource", sysSource);
                builder.addTextBody("isMultiVersion", isMultiVersion);
                HttpEntity entity = builder.build();
                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost);// 执行提交
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) return EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
            } catch (IOException e) {
                log.warn("execute failed", e);
            }
        }
        return null;
    }

    @Override
    @Async
    public void download(UserInfo userInfo, List<FileFolder> fileFolders, String zipName, String id) throws JsonProcessingException {
        redisUtil.hset("fileSharing_download", id, LocalDateTime.now().toString());
        String url = fileManageAddress + ":" + fileManagePort + "/file/ossZipTree";
        ObjectMapper objectMapper = new ObjectMapper();
        String fileFoldersJson = objectMapper.writeValueAsString(fileFolders);
        String userInfoString = objectMapper.writeValueAsString(userInfo);
        String response = HttpUtil.httpRequestBody(url, userInfoString, fileFoldersJson, zipName);
        log.info(response);
        JSONObject jsonObject = new JSONObject(response);
        String data = jsonObject.getString("data");
        data = "http://hi.jl1.cn/fileapi" + data.split(fileManageUrl)[1];
        boolean flag;
        if (!data.startsWith("http")) flag = downloadService.updateDownload(id, data, "-1");
        else {
            flag = downloadService.updateDownload(id, data, "1");
            redisUtil.hdel("fileSharing_download", id);
        }
        if (!flag) log.warn("{}的下载队列修改失败!", userInfo.getUserName());
    }

    @Scheduled(cron = "0 */3 * * * ?")
    public void monitorDownload() {
        Map<String, String> map = redisUtil.hmget("fileSharing_download");
        LocalDateTime now = LocalDateTime.now();
        Set<String> removeKeys = new HashSet<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            LocalDateTime localDateTime = LocalDateTime.parse(entry.getValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));
            if (Duration.between(localDateTime, now).getSeconds() > 6 * 60) {
                //删除redis相应下载任务
                log.info("{}下载超时", entry.getKey());
                removeKeys.add(entry.getKey());
                //修改下载任务状态
                if (!downloadService.updateDownload(entry.getKey(), null, "-1"))
                    log.warn("{}的下载队列修改失败!", entry.getKey());
            }
        }
        for (String key : removeKeys) redisUtil.hdel("fileSharing_download", key);
    }

    @Override
    @Transactional
    public String updateParentTime(String entityId) {
        String parent = "";
        if (entityId.startsWith("folder")) {
            Folder folder = new Folder();
            folder.setEntityId(entityId);
            List<Folder> folders = folderMapper.getFolder(folder);
            if (folders.isEmpty()) {
                PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                personalRecycleBin.setEntityId(entityId);
                List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
                if (personalRecycleBins.isEmpty()) {
                    log.error("updateParentTime: 不存在该entityId!(1)");
                    throw new BusinessException("不存在该entityId!");
                } else parent = personalRecycleBins.get(0).getParentId();
            } else parent = folders.get(0).getParentId();
        } else if (entityId.startsWith("file")) {
            File file = new File();
            file.setEntityId(entityId);
            List<File> files = fileMapper.getFile(file);
            if (files.isEmpty()) {
                PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                personalRecycleBin.setEntityId(entityId);
                List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
                if (personalRecycleBins.isEmpty()) {
                    log.error("updateParentTime: 不存在该entityId!(2)");
                    throw new BusinessException("不存在该entityId!");
                } else parent = personalRecycleBins.get(0).getParentId();
            } else parent = files.get(0).getParentId();
        }
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        while (!parent.equals("root")) {
            Folder folder = new Folder();
            folder.setEntityId(parent);
            List<Folder> folders = folderMapper.getFolder(folder);
            if (folders.isEmpty()) {
                log.error("updateParentTime: 不存在该entityId!(3)");
                throw new BusinessException("不存在该entityId!");
            }
            folder = folders.get(0);
            folder.setUpdateTime(time);
            if (!folderMapper.updateFolderById(folder)) {
                log.error("updateParentTime: 时间修改失败!");
                throw new BusinessException("updateParentTime: 时间修改失败!");
            }
            parent = folder.getParentId();
            //修改收藏和分享
            Favorites favorites = new Favorites();
            favorites.setEntityId(parent);
            List<Favorites> favoritesList = favoritesMapper.getFavorites(favorites);
            if (!favoritesList.isEmpty()) {
                favorites = favoritesList.get(0);
                favorites.setUpdateTime(time);
                if (!favoritesMapper.updateFavoritesName(favorites)) {
                    log.error("收藏修改失败!(1)");
                    throw new BusinessException("收藏修改失败!");
                }
            }
            Shared shared = new Shared();
            shared.setEntityId(parent);
            List<Shared> shareds = sharedMapper.getShared(shared);
            if (!shareds.isEmpty()) {
                shared = shareds.get(0);
                shared.setUpdateTime(time);
                if (!sharedMapper.updateSharedName(shared)) {
                    log.error("收藏修改失败!(2)");
                    throw new BusinessException("收藏修改失败!");
                }
            }
        }
        return "修改时间修改成功!";
    }

    @Transactional
    @Override
    public String uploadFile(String account, String name, String deptId, String roomId, String parentId, String type, MultipartFile multipartFile, String isOuter) {
        String entityId = fileService.generateEntityId();
        if (type != null && (type.equals("dept") || type.equals("company"))) {
            int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, parentId));
            if (level < 3) throw new BusinessException("您没有编辑权限!");
            //自己的管理权限
            if (!authorityService.initAuthority(account, name, entityId, "4").equals("新增权限成功!")) {
                log.error("新增权限失败!(1)");
                throw new BusinessException("新增权限失败!");
            }
        }
        float fileSize = getFileSize(multipartFile);
        //检查剩余空间够不够了
        Room room = new Room();
        room.setId(roomId);
        room = roomService.getRoom(room).get(0);
        if (room.getUsedSpace() + fileSize > roomSize) throw new BusinessException("空间不足，请删除不需要的文件!");
        String fileInfo = upload(multipartFile, account, fileSize, isOuter);
        log.info("fileInfo:  {}", fileInfo);
        if (fileInfo == null) {
            log.error("文件管理系统上传失败(1)");
            throw new BusinessException("文件管理系统上传失败!");
        }
        JSONObject jsonObject = new JSONObject(fileInfo);
        String message = jsonObject.getString("message");
        if (!message.equals("success")) {
            log.info("fileInfo:  {}", fileInfo);
            log.error("上传失败");
            throw new BusinessException("上传失败!");
        }
        JSONArray dataArray = jsonObject.getJSONArray("data");
        JSONObject dataObj = dataArray.getJSONObject(0);
        String fileUrl = dataObj.getString("fileUrl");
        String fileId = dataObj.getString("fileId");
        String fileName = dataObj.getString("fileName");
        //检查重名文件（夹）
        File file = new File();
        file.setParentId(parentId);
        List<File> files = fileMapper.getFile(file);
        Set<String> set = new HashSet<>();
        for (File file0 : files) set.add(file0.getEntityName() + "." + file0.getType());
        while(set.contains(fileName)) fileName = "副本-" + fileName;
        String result = fileService.insertFile(account, name, entityId, roomId, parentId, fileId, fileName, fileUrl, fileSize);
        if (!result.equals("新增成功!")) {
            log.error("文件新增失败!");
            throw new BusinessException("文件新增失败!");
        }
        //空间大小
        room.setUsedSpace(fileSize);
        if (!roomService.updateRoomById(room).equals("更新成功!")) {
            log.error("空间大小更新失败!");
            throw new BusinessException("空间大小更新失败!");
        }
        if (type != null && (type.equals("dept") || type.equals("company"))) {
            //继承父类权限
            Timestamp time = Timestamp.valueOf(LocalDateTime.now());
            List<Authority> authorities = authorityService.getAuthority(account, parentId);
            for (Authority authority : authorities) {
                authority.setId(authorityService.generateId());
                authority.setEntityId(entityId);
                authority.setEntityName(fileName.toString());
                authority.setCreateTime(time);
                authority.setUpdateTime(time);
                if (authority.getAuthorityLevel().equals("-1")) continue;
                authorityService.insertAuthority(authority);
            }
        }
        return fileId;
    }

    @Transactional
    @Override
    public String insertNonProject(String account, String name, String roomId, String parentId, String fileUrl, String fileId, String fileName, String managerUserId, String managerUserName) {
        String entityId = fileService.generateEntityId();
        String result = fileService.insertFile(account, name, entityId, roomId, parentId, fileId, fileName, fileUrl, 0);
        if (!result.equals("新增成功!")) {
            log.error("insertNonProject: 文件新增失败!");
            throw new BusinessException("文件新增失败!");
        }
        //继承父类权限
        Authority authority0 = new Authority();
        authority0.setEntityId(parentId);
        List<Authority> authorities = authorityService.getAuthority(authority0);
//        List<Authority> authorities = authorityService.getAuthority(account, parentId);
        Timestamp time = Timestamp.valueOf(LocalDateTime.now());
        for (Authority authority : authorities) {
            authority.setId(authorityService.generateId());
            authority.setEntityId(entityId);
            authority.setEntityName(fileName);
            authority.setFileOrFolder("file");
            authority.setCreateTime(time);
            authority.setUpdateTime(time);
            if (!authorityService.insertAuthority(authority)) {
                log.error("insertNonProject: 权限继承失败!");
                throw new BusinessException("权限继承失败!");
            }
        }
        //创建人管理权限
        Authority authority = new Authority();
        authority.setId(authorityService.generateId());
        authority.setEntityId(entityId);
        authority.setEntityName(fileName);
        authority.setFileOrFolder("file");
        authority.setAuthorityLevel("4");
        authority.setPermissionType("staff");
        authority.setPermissionId(account);
        authority.setPermissionName(name);
        authority.setCreateTime(time);
        authority.setUpdateTime(time);
        authorityService.insertAuthority(authority);
        authority.setId(authorityService.generateId());
        authority.setPermissionId(managerUserId);
        authority.setPermissionName(managerUserName);
        authorityService.insertAuthority(authority);
        return entityId;
    }

    @Transactional
    @Override
    public String updateFile(String ownerAccount, String ownerName, String entityName, String fileId, String fileUrl, String entityId, String versionId) {
        File file = new File();
        file.setEntityId(entityId);
        file = fileMapper.getFile(file).get(0);
        file.setOwnerAccount(ownerAccount);
        file.setOwnerName(ownerName);
        file.setEntityName(entityName);
        file.setFileId(fileId);
        file.setFileUrl(fileUrl);
        file.setVersionId(versionId);
        file.setUpdateTime(Timestamp.valueOf(LocalDateTime.now()));
        log.info("updateFile: {}", file);
        String result = fileService.updateFileById(file);
        if (!result.equals("更新成功!")) {
            log.error("uploadVersionFile: 文件更新失败!");
            throw new BusinessException("文件更新失败!");
        }
        //已经继承父类权限，无需再加
        return result;
    }

    @Override
    public List<MinioFileVersion> getVersionFile(String fileId) {
        return minioFileVersionMapper.getByFileId(fileId);
    }

    @Override
    public String addTags(String account, String deptId, String entityId, List<String> tags, String type) {
        //子继承父亲标签
        if (type != null && (type.equals("dept") || type.equals("company"))) {
            int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, entityId));
            if (level < 3) throw new BusinessException("您没有编辑权限!");
        }
        StringBuilder newTags = new StringBuilder();
        for (String tag : tags) {
            newTags.append(",").append(tag);
        }
        if (entityId.startsWith("folder")) {
            List<String> fileFolders = authorityService.getChildrenAndMyself(entityId);
            for (String fileFolder : fileFolders) {
                if (fileFolder.startsWith("folder")) {
                    Folder folder = new Folder();
                    folder.setEntityId(entityId);
                    folder = folderService.getFolder(folder).get(0);
                    if (folder.getTag() == null || folder.getTag().isEmpty())
                        folder.setTag(newTags.substring(1, newTags.length()));
                    else folder.setTag(folder.getTag() + newTags);
                    if (!folderService.updateFolderById(folder).equals("更新成功!"))
                        throw new BusinessException("标签添加失败!");
                } else {
                    File file = new File();
                    file.setEntityId(entityId);
                    file = fileMapper.getFile(file).get(0);
                    if (file.getTag() == null || file.getTag().isEmpty())
                        file.setTag(newTags.substring(1, newTags.length()));
                    else file.setTag(file.getTag() + newTags);
                    if (!fileService.updateFileById(file).equals("更新成功!"))
                        throw new BusinessException("标签添加失败!");
                }
            }
        } else {
            File file = new File();
            file.setEntityId(entityId);
            file = fileMapper.getFile(file).get(0);
            if (file.getTag() == null || file.getTag().isEmpty()) file.setTag(newTags.substring(1, newTags.length()));
            else file.setTag(file.getTag() + newTags);
            if (!fileService.updateFileById(file).equals("更新成功!")) throw new BusinessException("标签添加失败!");
        }
        return "标签添加成功!";
    }

    @Override
    public String getURLByFileId(String account, String deptId, String entityId, String type) {
        File file = new File();
        if (type != null && (type.equals("dept") || type.equals("company"))) {
            int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, entityId));
            if (level < 2) {
                file.setEntityId(entityId);
                return "您没有" + fileService.getFile(file).get(0).getEntityName() + "的下载权限!";
            }
        }
        file.setEntityId(entityId);
        List<File> files = fileService.getFile(file);
        String url;
        if (files.isEmpty()) url = null;
        else {
            file = files.get(0);
            url = file.getFileUrl();
            file.setDownloadTimes(file.getDownloadTimes() + 1);
            fileMapper.updateFileById(file);
        }
        url = "http://hi.jl1.cn/fileapi" + url.split(fileManageUrl)[1];
        if (files.isEmpty()) return "entityId有误!";
        return url;
    }

    @Override
    public List<FileFolder> downloadFolder(String account, String deptId, String entityId, String type) {
        Folder folder = new Folder();
        folder.setEntityId(entityId);
        folder = folderService.getFolder(folder).get(0);
        List<FileFolder> fileFolders = authorityService.getChildrenAndMyself2(entityId);
        List<FileFolder> fileFoldersAuthority = new ArrayList<>();
        if (type != null && (type.equals("dept") || type.equals("company"))) {
            for (FileFolder fileFolder : fileFolders) {
                int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, fileFolder.getEntityId()));
                if (level > 1) fileFoldersAuthority.add(fileFolder);
            }
        } else fileFoldersAuthority = fileFolders;
        fileFoldersAuthority = TreeUtils.build(fileFoldersAuthority, folder.getParentId());
        return fileFoldersAuthority;
    }

    @Override
    public String getFileLocalDateTime() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d/HHmmss");
        String formattedDateTime = now.format(formatter);
        String secondFraction = String.format("%04d", now.getSecond() % 100);
        return formattedDateTime.substring(0, formattedDateTime.length() - 2) + secondFraction;
    }

    @Override
    @Transactional
    public String delete(String account, String deptId, List<String> entityIds, String type) {
        String result = null;
        boolean tag = false;
        for (String entityId : entityIds) {
            if (type != null && (type.equals("dept") || type.equals("company"))) {
                int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, entityId));
                if (level >= 3) {
                    if (entityId.startsWith("folder")) {
                        Folder folder = new Folder();
                        folder.setEntityId(entityId);
                        List<Folder> folders = folderService.getFolder(folder);
                        if (folders.isEmpty()) {
                            log.error("entityId{}不存在!", entityId);
                            throw new BusinessException("entityId" + entityId + "不存在!");
                        }
                        //遍历子文件（夹）的编辑权限
                        File file = new File();
                        file.setParentId(entityId);
                        List<File> files = fileMapper.getFile(file);
                        for (File file1 : files)
                            if (Integer.parseInt(authorityService.checkAuthority(account, deptId, file1.getEntityId())) < 3)
                                throw new BusinessException("您没有子文件的编辑权限!");
                        Folder parentFolder = new Folder();
                        parentFolder.setEntityId(entityId);
                        String roomId = folderService.getFolder(parentFolder).get(0).getEntityRoom();
                        folders = folderMapper.getAllFolderByRoomId(roomId);
                        folders = TreeUtils.build(folders, entityId);
                        for (Folder folder0 : folders) {
                            if (Integer.parseInt(authorityService.checkAuthority(account, deptId, folder0.getEntityId())) < 3)
                                throw new BusinessException("您没有子文件夹的编辑权限!");
                            List<Folder> folders1 = TreeUtils.root2List(folder0);
                            for (Folder folder1 : folders1) {
                                if (Integer.parseInt(authorityService.checkAuthority(account, deptId, folder1.getEntityId())) < 3)
                                    throw new BusinessException("您没有子文件夹的编辑权限!");
                                file = new File();
                                file.setParentId(folder1.getEntityId());
                                files = fileMapper.getFile(file);
                                for (File file1 : files)
                                    if (Integer.parseInt(authorityService.checkAuthority(account, deptId, file1.getEntityId())) < 3)
                                        throw new BusinessException("您没有子文件的编辑权限!");
                            }
                        }
                    }
                } else {
                    String entityName;
                    if (entityId.startsWith("folder")) {
                        Folder folder = new Folder();
                        folder.setEntityId(entityId);
                        List<Folder> folders = folderService.getFolder(folder);
                        if (folders.isEmpty()) {
                            log.error("entityId{}不存在!(1)", entityId);
                            throw new BusinessException("entityId" + entityId + "不存在!");
                        }
                        folder = folders.get(0);
                        entityName = folder.getEntityName();
                    } else {
                        File file = new File();
                        file.setEntityId(entityId);
                        List<File> files = fileService.getFile(file);
                        if (files.isEmpty()) {
                            log.error("entityId{}不存在!(2)", entityId);
                            throw new BusinessException("entityId" + entityId + "不存在!");
                        }
                        file = files.get(0);
                        entityName = file.getEntityName();
                    }
                    throw new BusinessException("您没有" + entityName + "的编辑权限!");
                }
            }
            if (entityId.startsWith("file")) {
                File file = new File();
                file.setEntityId(entityId);
                List<File> files = fileService.getFile(file);
                if (files.get(0).getTag() != null && files.get(0).getTag().equals("签批文件")) {
                    Map<String, String> map = new HashMap<>();
                    map.put("entityId", entityId);
                    if (files.get(0).getEntityRoom().equals("0")) map.put("type", "company");
                    else if (files.get(0).getEntityRoom().startsWith("dept")) map.put("type", "dept");
                    getMethod(nonPj + "/nonPj/deleteNonPj", map);
                    tag = true;
                    result = "回收站新增文件(夹)成功!";
                } else result = personalRecycleBinService.insertRecycleBin(entityId, account);
            } else result = personalRecycleBinService.insertRecycleBin(entityId, account);
            if (!result.equals("回收站新增文件(夹)成功!")) {
                log.error("回收站新增失败!");
                throw new BusinessException("回收站新增失败!");
            } else {
                //收藏和分享得改
                List<String> allChildren;
                if (entityId.startsWith("folder")) allChildren = authorityService.getChildrenAndMyself(entityId);
                else allChildren = Collections.singletonList(entityId);
                Favorites favorites = new Favorites();
                Shared shared = new Shared();
                if (!allChildren.isEmpty()) {
                    Folder folder = new Folder();
                    File file = new File();
                    for (String children : allChildren) {
                        favorites.setEntityId(children);
                        favorites.setIsDeleted("false");
                        if (!favoritesMapper.getFavorites(favorites).isEmpty()) {
                            favorites.setIsDeleted("true");
                            if (!favoritesMapper.updateFavoritesDeleted(favorites)) {
                                log.error("收藏删除失败!(1)");
                                throw new BusinessException("收藏删除失败!");
                            }
                        }
                        shared.setEntityId(children);
                        shared.setIsDeleted("false");
                        if (!sharedMapper.getShared(shared).isEmpty()) {
                            shared.setIsDeleted("true");
                            if (!sharedMapper.updateSharedDeleted(shared)) {
                                log.error("分享删除失败!(1)");
                                throw new BusinessException("分享删除失败!");
                            }
                        }
                        if (children.startsWith("folder")) {
                            folder.setEntityId(children);
                            if (!folderMapper.getFolder(folder).isEmpty()) {
                                folder.setIsDeleted("true");
                                if (!folderMapper.updateFolderById(folder)) {
                                    log.error("子文件夹删除失败!(1)");
                                    throw new BusinessException("子文件夹删除失败!");
                                }
                            }
                        } else {
                            file.setEntityId(children);
                            if (!fileMapper.getFile(file).isEmpty()) {
                                file.setIsDeleted("true");
                                if (!fileMapper.updateFileById(file)) {
                                    log.error("子文件删除失败!(1)");
                                    throw new BusinessException("子文件删除失败!");
                                }
                            }
                        }
                    }
                }
                if (entityId.startsWith("folder")) result = folderService.deleteFolderById(entityId);
                else if (entityId.startsWith("file")) result = fileService.deleteFileById(entityId);
                else {
                    log.error("entityId有误");
                    throw new BusinessException("entityId有误!");
                }
                if (result.equals("删除失败!")) {
                    log.error("删除失败");
                    throw new BusinessException("删除失败!");
                }
                if (!tag) {
                    if (!updateParentTime(entityId).equals("修改时间修改成功!")) {
                        log.error("修改时间修改失败!");
                        throw new BusinessException("修改时间修改失败!");
                    }
                }
            }
        }
        return result;
    }

    @Override
    @Transactional
    public String restore(String account, String deptId, List<String> entityIds, String type) {
        String result;
        for (String entityId : entityIds) {
            PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
            personalRecycleBin.setEntityId(entityId);
            List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinService.getPersonalRecycleBin(personalRecycleBin);
            if (personalRecycleBins.isEmpty()) {
                log.error("回收站中无此文件（夹）!");
                throw new BusinessException("回收站中无此文件（夹）!");
            }
            personalRecycleBin = personalRecycleBins.get(0);
            // 若该文件（夹）不是根节点，且父亲路径若不在，则添加这条路径
            if (personalRecycleBin.getParentPath() != null && !personalRecycleBin.getParentPath().isEmpty()) {
                String[] parentPath = personalRecycleBin.getParentPath().split(",");
                String parentId = "root";
                Folder folder = new Folder();
                List<Folder> folders;
                // 1.在Folder中 2.它的parentId确实是parentId
                for (String parent : parentPath) {
                    folder.setEntityId(parent);
                    folders = folderService.getFolder(folder);
                    //原路径不存在
                    if (folders.isEmpty() || !folders.get(0).getParentId().equals(parentId))
                        throw new BusinessException("原路径不存在!");
                    parentId = folders.get(0).getEntityId();
                }
            }
            //收藏和分享得改
            List<String> allChildren;
            if (entityId.startsWith("folder")) allChildren = authorityService.getChildrenAndMyselfRecycleBin(entityId);
            else allChildren = Collections.singletonList(entityId);
            Favorites favorites = new Favorites();
            Shared shared = new Shared();
            if (!allChildren.isEmpty()) {
                Folder folder = new Folder();
                File file = new File();
                for (String folder1 : allChildren) {
                    favorites.setEntityId(folder1);
                    favorites.setIsDeleted("true");
                    if (!favoritesMapper.getFavorites(favorites).isEmpty()) {
                        favorites.setIsDeleted("false");
                        if (!favoritesMapper.updateFavoritesDeleted(favorites)) {
                            log.error("收藏恢复失败!(1)");
                            throw new BusinessException("收藏恢复失败!");
                        }
                    }
                    shared.setEntityId(folder1);
                    shared.setIsDeleted("true");
                    if (!sharedMapper.getShared(shared).isEmpty()) {
                        shared.setIsDeleted("false");
                        if (!sharedMapper.updateSharedDeleted(shared)) {
                            log.error("收藏恢复失败!(3)");
                            throw new BusinessException("分享恢复失败!");
                        }
                    }
                    if (folder1.startsWith("folder")) {
                        folder.setEntityId(folder1);
                        folder.setIsDeleted("true");
                        if (!folderMapper.getFolder(folder).isEmpty()) {
                            folder.setIsDeleted("false");
                            if (!folderMapper.updateFolderById(folder)) {
                                log.error("子文件夹恢复失败!(1)");
                                throw new BusinessException("子文件夹恢复失败!");
                            }
                        }
                    } else {
                        file.setEntityId(folder1);
                        file.setIsDeleted("true");
                        if (!fileMapper.getFile(file).isEmpty()) {
                            file.setIsDeleted("false");
                            if (!fileMapper.updateFileById(file)) {
                                log.error("子文件恢复失败!(1)");
                                throw new BusinessException("子文件恢复失败!");
                            }
                        }
                    }
                }
            }
            if (entityId.startsWith("folder")) {
                Folder folder = new Folder();
                folder.setEntityName(personalRecycleBin.getEntityName());
                folder.setParentId(personalRecycleBin.getParentId());
                List<Folder> folders2 = folderMapper.getFolder(folder);
                if (!folders2.isEmpty()) throw new BusinessException("存在重名文件夹!");

                folder.setEntityId(entityId);
                folder.setEntityRoom(personalRecycleBin.getEntityRoom());
                folder.setType(personalRecycleBin.getType());
                folder.setTag(personalRecycleBin.getTag());
                folder.setOwnerAccount(personalRecycleBin.getOwnerAccount());
                folder.setOwnerName(personalRecycleBin.getOwnerName());
                folder.setCreateTime(personalRecycleBin.getCreateTime());
                folder.setUpdateTime(personalRecycleBin.getUpdateTime());
                result = String.valueOf(folderMapper.insertFolder(folder));
            } else if (entityId.startsWith("file")) {
                //检查重名文件
                File file = new File();
                file.setParentId(personalRecycleBin.getParentId());
                List<File> files = fileMapper.getFile(file);
                for (File file0 : files) {
                    if ((file0.getEntityName() + "." + file0.getType()).equals(personalRecycleBin.getEntityName() + "." + personalRecycleBin.getType()))
                        throw new BusinessException("存在重名文件!");
                }

                file = new File();
                file.setEntityId(entityId);
                file.setEntityName(personalRecycleBin.getEntityName());
                file.setEntityRoom(personalRecycleBin.getEntityRoom());
                file.setParentId(personalRecycleBin.getParentId());
                file.setType(personalRecycleBin.getType());
                file.setTag(personalRecycleBin.getTag());
                file.setOwnerAccount(personalRecycleBin.getOwnerAccount());
                file.setOwnerName(personalRecycleBin.getOwnerName());
                file.setCreateTime(personalRecycleBin.getCreateTime());
                file.setUpdateTime(personalRecycleBin.getUpdateTime());
                file.setFileId(personalRecycleBin.getFileId());
                file.setFileUrl(personalRecycleBin.getFileUrl());
                file.setVersionId(personalRecycleBin.getVersionId());
                result = String.valueOf(fileMapper.insertFile(file));
            } else {
                log.error("entityId有误!");
                throw new BusinessException("entityId有误!");
            }
            if (result.equals("true")) result = personalRecycleBinService.deletePersonalRecycleBinById(entityId);
            else {
                log.error("文件（夹）恢复失败!(1)");
                throw new BusinessException("文件（夹）恢复失败!");
            }
            if (!result.equals("删除成功!")) {
                log.error("文件（夹）恢复失败!(2)");
                throw new BusinessException("文件（夹）恢复失败!");
            }
            if (!updateParentTime(entityId).equals("修改时间修改成功!")) {
                log.error("修改时间修改失败!(2)");
                throw new BusinessException("修改时间修改失败!");
            }
        }
        return "文件（夹）恢复成功!";
    }

    @Override
    @Transactional
    public String removeRecycleBin(String account, String deptId, String entityId, String parentId, String type) {
        String result = "";
        PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
        personalRecycleBin.setEntityId(entityId);
        List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
        if (personalRecycleBins.isEmpty()) {
            log.error("回收站中不存在该entityId!");
            throw new BusinessException("回收站中不存在该entityId!");
        }
        personalRecycleBin = personalRecycleBins.get(0);

        //收藏和分享得改
        List<Folder> folders;
        List<Folder> allChildren = new ArrayList<>();
        if (entityId.startsWith("folder")) {
            //获取子文件夹
            PersonalRecycleBin personalRecycleBin1 = new PersonalRecycleBin();
            personalRecycleBin1.setEntityId(entityId);
            personalRecycleBin1 = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin1).get(0);
            String roomId = personalRecycleBin1.getEntityRoom();
            folders = folderMapper.getAllFolderByRoomId(roomId);
            folders = TreeUtils.build(folders, entityId);
            for (Folder folder1 : folders) {
                List<Folder> folders1 = TreeUtils.root2List(folder1);
                allChildren.addAll(folders1);
            }
        }
        Favorites favorites = new Favorites();
        favorites.setEntityId(entityId);
        if (!allChildren.isEmpty()) {
            for (Folder folder1 : allChildren) {
                favorites.setEntityId(folder1.getEntityId());
                favorites.setIsDeleted("true");
                if (!favoritesMapper.getFavorites(favorites).isEmpty()) {
                    favorites.setIsDeleted("false");
                    if (!favoritesMapper.updateFavoritesDeleted(favorites)) {
                        log.error("收藏恢复失败!(5)");
                        throw new BusinessException("收藏恢复失败!");
                    }
                }
            }
        }
        favorites.setIsDeleted("true");
        favorites.setEntityId(entityId);
        if (!favoritesMapper.getFavorites(favorites).isEmpty()) {
            favorites.setIsDeleted("false");
            if (!favoritesMapper.updateFavoritesDeleted(favorites)) {
                log.error("收藏恢复失败!(6)");
                throw new BusinessException("收藏恢复失败!");
            }
        }
        Shared shared = new Shared();
        shared.setEntityId(entityId);
        if (!allChildren.isEmpty()) {
            for (Folder folder1 : allChildren) {
                shared.setEntityId(folder1.getEntityId());
                shared.setIsDeleted("true");
                if (!sharedMapper.getShared(shared).isEmpty()) {
                    shared.setIsDeleted("false");
                    if (!sharedMapper.updateSharedDeleted(shared)) {
                        log.error("分享恢复失败!(1)");
                        throw new BusinessException("分享恢复失败!");
                    }
                }
            }
        }
        shared.setIsDeleted("true");
        shared.setEntityId(entityId);
        if (!sharedMapper.getShared(shared).isEmpty()) {
            shared.setIsDeleted("false");
            if (!sharedMapper.updateSharedDeleted(shared)) {
                log.error("分享恢复失败!(2)");
                throw new BusinessException("分享恢复失败!");
            }
        }
        if (entityId.startsWith("folder")) {
            Folder folder = new Folder();
            folder.setEntityId(parentId);
            folders = folderMapper.getFolder(folder);
            if (folders.isEmpty()) {
                log.error("parentId有误!");
                throw new BusinessException("parentId有误!");
            }
            folder = new Folder();
            folder.setParentId(parentId);
            folder.setEntityName(personalRecycleBin.getEntityName());
            folders = folderMapper.getFolder(folder);
            if (!folders.isEmpty()) throw new BusinessException("移动到的文件夹存在重名文件夹!");
            folder = new Folder();
            folder.setEntityId(entityId);
            folder.setEntityName(personalRecycleBin.getEntityName());
            folder.setEntityRoom(personalRecycleBin.getEntityRoom());
            folder.setParentId(parentId);
            folder.setType(personalRecycleBin.getType());
            folder.setTag(personalRecycleBin.getTag());
            folder.setOwnerAccount(personalRecycleBin.getOwnerAccount());
            folder.setOwnerName(personalRecycleBin.getOwnerName());
            folder.setCreateTime(personalRecycleBin.getCreateTime());
            folder.setUpdateTime(personalRecycleBin.getUpdateTime());
            result = String.valueOf(folderMapper.insertFolder(folder));
        } else if (entityId.startsWith("file")) {
            Folder folder = new Folder();
            folder.setEntityId(parentId);
            List<Folder> folders1 = folderMapper.getFolder(folder);
            if (folders1.isEmpty()) {
                log.error("parentId有误!(2)");
                throw new BusinessException("parentId有误!");
            }
            File file = new File();
            file.setParentId(parentId);
            file.setEntityName(personalRecycleBin.getEntityName());
            List<File> files = fileMapper.getFile(file);
            if (!files.isEmpty()) throw new BusinessException("移动到的文件夹存在重名文件!");
            file = new File();
            file.setEntityId(entityId);
            file.setEntityName(personalRecycleBin.getEntityName());
            file.setEntityRoom(personalRecycleBin.getEntityRoom());
            file.setParentId(parentId);
            file.setType(personalRecycleBin.getType());
            file.setTag(personalRecycleBin.getTag());
            file.setOwnerAccount(personalRecycleBin.getOwnerAccount());
            file.setOwnerName(personalRecycleBin.getOwnerName());
            file.setCreateTime(personalRecycleBin.getCreateTime());
            file.setUpdateTime(personalRecycleBin.getUpdateTime());
            file.setFileId(personalRecycleBin.getFileId());
            file.setFileUrl(personalRecycleBin.getFileUrl());
            file.setVersionId(personalRecycleBin.getVersionId());
            result = String.valueOf(fileMapper.insertFile(file));
        }
        if (!personalRecycleBinMapper.deletePersonalRecycleBinById(entityId)) {
            log.error("回收站删除失败!(2)");
            throw new BusinessException("回收站删除失败!");
        }
        if (!updateParentTime(entityId).equals("修改时间修改成功!")) {
            log.error("修改时间修改失败!(3)");
            throw new BusinessException("修改时间修改失败!");
        }
        return result;
    }

    @Transactional
    @Override
    public String rename(String account, String deptId, String entityName, String entityId, String parentId, String type) {
        if (type != null && (type.equals("dept") || type.equals("company"))) {
            int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, entityId));
            if (level < 3) throw new BusinessException("您没有编辑权限!");
        }
        boolean flag;
        Timestamp time = (Timestamp.valueOf(LocalDateTime.now()));
        if (entityId.startsWith("folder")) {
            Folder folder = new Folder();
            folder.setEntityId(entityId);
            folder.setParentId(parentId);
            List<Folder> folders = folderMapper.getFolder(folder);
            if (folders.isEmpty()) {
                log.error("entityId或parentId有误!(1)");
                throw new BusinessException("entityId或parentId有误!");
            }
            folder.setEntityName(entityName);
            folder.setEntityId(null);
            folders = folderMapper.getFolder(folder);
            if (!folders.isEmpty()) throw new BusinessException("存在重名文件夹!");
            folder.setEntityId(entityId);
            folder.setUpdateTime(time);
            flag = folderMapper.updateFolderById(folder);
        } else if (entityId.startsWith("file")) {
            File file = new File();
            file.setEntityId(entityId);
            file.setParentId(parentId);
            List<File> files = fileMapper.getFile(file);
            if (files.isEmpty()) {
                log.error("entityId或parentId有误!(2)");
                throw new BusinessException("entityId或parentId有误!");
            }
            file.setEntityName(entityName);
            file.setEntityId(null);
            files = fileMapper.getFile(file);
            if (!files.isEmpty()) throw new BusinessException("存在重名文件夹!");
            file.setUpdateTime(time);
            file.setEntityId(entityId);
            file.setFileSize(file.getFileSize());
            flag = fileMapper.updateFileById(file);
        } else {
            log.error("entityId有误!(2)");
            throw new BusinessException("entityId有误!");
        }
        if (!flag) {
            log.error("重命名失败!");
            throw new BusinessException("重命名失败!");
        } else {
            //修改收藏和分享
            Favorites favorites = new Favorites();
            favorites.setEntityId(entityId);
            if (!favoritesMapper.getFavorites(favorites).isEmpty()) {
                favorites.setEntityName(entityName);
                favorites.setUpdateTime(time);
                if (!favoritesMapper.updateFavoritesName(favorites)) {
                    log.error("收藏修改失败!");
                    throw new BusinessException("收藏修改失败!");
                }
            }
            Shared shared = new Shared();
            shared.setEntityId(entityId);
            if (!sharedMapper.getShared(shared).isEmpty()) {
                shared.setEntityName(entityName);
                shared.setUpdateTime(time);
                if (!sharedMapper.updateSharedName(shared)) {
                    log.error("收藏修改失败!(3))");
                    throw new BusinessException("收藏修改失败!");
                }
            }
        }
        if (!updateParentTime(entityId).equals("修改时间修改成功!")) {
            log.error("修改时间修改失败!(4)");
            throw new BusinessException("修改时间修改失败!");
        }
        return "重命名成功!";
    }

    @Override
    @Transactional
    public String remove(String account, String deptId, String entityId, String parentId, String type) {
        Folder parentFolder = new Folder();
        parentFolder.setEntityId(parentId);
        String roomId = folderService.getFolder(parentFolder).get(0).getEntityRoom();
        if (type != null && (type.equals("dept") || type.equals("company"))) {
            int level = Integer.parseInt(authorityService.checkAuthority(account, deptId, parentId));
            if (level < 3) throw new BusinessException("您没有移动到的文件夹的编辑权限!");
            level = Integer.parseInt(authorityService.checkAuthority(account, deptId, entityId));
            if (level < 3) throw new BusinessException("您没有该文件（夹）的编辑权限!");
            //权限
            if (entityId.startsWith("folder")) {
                //遍历子文件（夹）的编辑权限
                File file = new File();
                file.setParentId(entityId);
                List<File> files = fileMapper.getFile(file);
                for (File file1 : files)
                    if (Integer.parseInt(authorityService.checkAuthority(account, deptId, file1.getEntityId())) < 3)
                        throw new BusinessException("您没有子文件的编辑权限!");
                List<Folder> folders = folderMapper.getAllFolderByRoomId(roomId);
                folders = TreeUtils.build(folders, entityId);
                for (Folder folder : folders) {
                    if (Integer.parseInt(authorityService.checkAuthority(account, deptId, folder.getEntityId())) < 3)
                        throw new BusinessException("您没有子文件夹的编辑权限!");
                    List<Folder> folders1 = TreeUtils.root2List(folder);
                    for (Folder folder1 : folders1) {
                        if (Integer.parseInt(authorityService.checkAuthority(account, deptId, folder1.getEntityId())) < 3)
                            throw new BusinessException("您没有子文件夹的编辑权限!");
                        file = new File();
                        file.setParentId(folder1.getEntityId());
                        files = fileMapper.getFile(file);
                        for (File file1 : files)
                            if (Integer.parseInt(authorityService.checkAuthority(account, deptId, file1.getEntityId())) < 3)
                                throw new BusinessException("您没有子文件的编辑权限!");
                    }
                }
            }
        }
        //移动到的文件夹存在重名文件（夹）
        if (entityId.startsWith("folder")) {
            Folder folder = new Folder();
            folder.setEntityId(entityId);
            List<Folder> folders = folderMapper.getFolder(folder);
            if (folders.isEmpty()) {
                log.error("不存在该entityId!");
                throw new BusinessException("不存在该entityId!");
            }
            String entityName = folders.get(0).getEntityName();
            folder = new Folder();
            folder.setEntityName(entityName);
            folder.setParentId(parentId);
            folders = folderMapper.getFolder(folder);
            if (!folders.isEmpty()) throw new BusinessException("移动到的文件夹存在重名文件夹!");
            //不能移动到自己的子文件夹
            folder = new Folder();
            folder.setEntityId(entityId);
            folders = folderMapper.getAllFolderByRoomId(roomId);
            folders = TreeUtils.build(folders, entityId);
            for (Folder folder1 : folders) {
                if (folder1.getEntityId().equals(parentId)) throw new BusinessException("不能移动到自己的子文件（夹）!");
            }
            if (entityId.equals(parentId)) throw new BusinessException("不能移动到自己的子文件（夹）!");
            folder.setEntityId(entityId);
            folder.setEntityName(entityName);
            folder.setParentId(parentId);
            Folder folderParent = new Folder();
            folderParent.setEntityId(parentId);
            folderParent = folderService.getFolder(folderParent).get(0);
            folder.setEntityRoom(folderParent.getEntityRoom());
            if (!folderMapper.updateFolderById(folder)) {
                log.error("文件夹移动失败!");
                throw new BusinessException("文件夹移动失败!");
            }
        } else if (entityId.startsWith("file")) {
            File file = new File();
            file.setEntityId(entityId);
            List<File> files = fileMapper.getFile(file);
            if (files.isEmpty()) {
                log.error("不存在该entityId!(2)");
                throw new BusinessException("不存在该entityId!");
            }
            file = files.get(0);
            String entityName = file.getEntityName();
            float size = file.getFileSize();
            file = new File();
            file.setEntityName(entityName);
            file.setParentId(parentId);
            files = fileMapper.getFile(file);
            if (!files.isEmpty()) throw new BusinessException("移动到的文件夹存在重名文件!");
            file.setEntityId(entityId);
            Folder folderParent = new Folder();
            folderParent.setEntityId(parentId);
            folderParent = folderService.getFolder(folderParent).get(0);
            file.setEntityRoom(folderParent.getEntityRoom());
            file.setFileSize(size);
            if (!fileMapper.updateFileById(file)) {
                log.error("文件移动失败!");
                throw new BusinessException("文件移动失败!");
            }
        } else throw new BusinessException("entityId有误!");
        if (!updateParentTime(entityId).equals("修改时间修改成功!")) {
            log.error("修改时间修改失败!(5)");
            throw new BusinessException("修改时间修改失败!");
        }
        return "文件（夹）移动成功!";
    }

    @Override
    public String getPathName(String parentId) {
        StringBuilder parentPathname = new StringBuilder();
        Room room = new Room();
        Folder folder = new Folder();
        while (parentId != null && !parentId.equals("root")) {
            folder = new Folder();
            folder.setEntityId(parentId);
            folder = folderMapper.getFolder(folder).get(0);
            parentPathname.insert(0, folder.getEntityName() + "/");
            parentId = folder.getParentId();
        }
        room.setId(folder.getEntityRoom());
        String roomName = roomService.getRoom(room).get(0).getRoomName();
        parentPathname.insert(0, roomName + "的空间/");
        return parentPathname.substring(0, parentPathname.length() - 1);
    }

    @Override
    public boolean isDeptLeader(String userId) {
        UsUser user = new UsUser();
        user.setAccount(userId);
        user = userMapper.getUser(user).get(0);
        String roles = user.getRoleId();
        String[] roleList = roles.split(",");
        for (String role : roleList) {
            if (role.equals("202207111752_8_role") || role.equals("202207111752_9_role") || role.equals("202207111752_10_role") || role.equals("202207111752_7_role"))
                return true;
        }
        return roles.equals("202207111752_8_role") || roles.equals("202207111752_9_role") || roles.equals("202207111752_10_role") || roles.equals("202207111752_7_role");
    }

    @Override
    public String getMethod(String url) {
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setContentCharset("UTF-8");
        GetMethod getMethod = new GetMethod(url);
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode == 200) {
                return getMethod.getResponseBodyAsString();
            } else {
                return "fail";
            }
        } catch (Exception var10) {
            log.warn(var10.getMessage());
            return "fail";
        } finally {
            getMethod.releaseConnection();
        }
    }

    @Override
    public String getMethod(String url, Map<String, String> map) {
        String result = "";
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                uriBuilder.addParameter(entry.getKey(), entry.getValue());
            }
            URI uri = uriBuilder.build();
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpGet httpGet = new HttpGet(uri);
                try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            result = EntityUtils.toString(entity, "UTF-8");
                            log.info(result);
                        }
                    } else log.error("请求失败，状态码：{}", response.getStatusLine().getStatusCode());
                }
            }

        } catch (URISyntaxException | IOException e) {
            log.error("getMethod: URI build error:{}", e.getCause().getMessage());
        }
        return result;
    }

    @Override
    public List<NpjManageDto> sortNpjManageDto(List<NpjManageDto> npjManageDtos, String column, String sort) {
        Comparator<NpjManageDto> comparator = null;
        switch (column) {
            case "originalFileName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjManageDto::getOriginalFileName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjManageDto::getOriginalFileName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileTitle,reportTitle,atlasTitle":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjManageDto::getFileTitle, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjManageDto::getFileTitle, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileNum":
                if (npjManageDtos != null && !npjManageDtos.isEmpty() && npjManageDtos.get(0).getFileInnerType().equals("程序文件")) {
                    if (sort.equals("desc")) comparator = (o1, o2) -> {
                        String[] s1 = o1.getFileNum().split("-");
                        String[] s2 = o2.getFileNum().split("-");
                        return s2[s2.length - 1].compareTo(s1[s1.length - 1]);
                    };
                    if (sort.equals("asc")) comparator = (o1, o2) -> {
                        String[] s1 = o1.getFileNum().split("-");
                        String[] s2 = o2.getFileNum().split("-");
                        return s1[s1.length - 1].compareTo(s2[s2.length - 1]);
                    };
                } else {
                    if (sort.equals("desc"))
                        comparator = Comparator.comparing(NpjManageDto::getFileNum, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                    if (sort.equals("asc"))
                        comparator = Comparator.comparing(NpjManageDto::getFileNum, Comparator.nullsLast(Comparator.naturalOrder()));
                }
                break;
            case "deptName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjManageDto::getDeptName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjManageDto::getDeptName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileStatus":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjManageDto::getFileStatus, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjManageDto::getFileStatus, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "bxName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjManageDto::getBxName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjManageDto::getBxName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "flowModifiedTime,flowCreatedTime":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjManageDto::getFlowModifiedTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjManageDto::getFlowModifiedTime, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
        }
        npjManageDtos.sort(comparator);
        return npjManageDtos;
    }

    @Override
    public List<NpjReportDto> sortNpjReportDto(List<NpjReportDto> npjReportDtos, String column, String sort) {
        Comparator<NpjReportDto> comparator = null;
        switch (column) {
            case "originalFileName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjReportDto::getOriginalFileName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjReportDto::getOriginalFileName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileTitle,reportTitle,atlasTitle":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjReportDto::getReportTitle, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjReportDto::getReportTitle, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileNum":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjReportDto::getFileNum, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjReportDto::getFileNum, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "deptName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjReportDto::getDeptName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjReportDto::getDeptName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileStatus":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjReportDto::getFileStatus, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjReportDto::getFileStatus, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "bxName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjReportDto::getBxName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjReportDto::getBxName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "flowModifiedTime,flowCreatedTime":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjReportDto::getFlowModifiedTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjReportDto::getFlowModifiedTime, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
        }
        npjReportDtos.sort(comparator);
        return npjReportDtos;
    }

    @Override
    public List<NpjFileFolder> sortGlobal(List<NpjFileFolder> npjFileFolders, String column, String sort) {
        Comparator<NpjFileFolder> comparator = null;
        switch (column) {
            case "type":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjFileFolder::getEntityId, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjFileFolder::getEntityId, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "entityName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjFileFolder::getEntityName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjFileFolder::getEntityName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "location,parentPathname":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjFileFolder::getLocation, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjFileFolder::getLocation, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileNum":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjFileFolder::getFileNum, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjFileFolder::getFileNum, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "tag":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjFileFolder::getTag, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjFileFolder::getTag, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "name,ownerName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjFileFolder::getOwnerName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjFileFolder::getOwnerName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "createTime":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjFileFolder::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjFileFolder::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
        }
        npjFileFolders.sort(comparator);
        return npjFileFolders;
    }

    @Override
    public List<NpjAtlasDto> sortNpjAtlasDto(List<NpjAtlasDto> npjAtlasDtos, String column, String sort) {
        Comparator<NpjAtlasDto> comparator = null;
        switch (column) {
            case "originalFileName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getOriginalFileName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getOriginalFileName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileTitle,reportTitle,atlasTitle":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getAtlasTitle, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getAtlasTitle, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileNum":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getFileNum, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getFileNum, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "deptName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getDeptName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getDeptName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "fileStatus":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getFileStatus, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getFileStatus, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "bxName":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getBxName, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getBxName, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
            case "flowModifiedTime,flowCreatedTime":
                if (sort.equals("desc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getFlowModifiedTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed();
                if (sort.equals("asc"))
                    comparator = Comparator.comparing(NpjAtlasDto::getFlowModifiedTime, Comparator.nullsLast(Comparator.naturalOrder()));
                break;
        }
        npjAtlasDtos.sort(comparator);
        return npjAtlasDtos;
    }

    @Override
    public String getEntityNameByEntityId(String entityId) {
        if (entityId == null || entityId.isEmpty()) return null;
        else {
            if (entityId.startsWith("folder")) {
                Folder folder = new Folder();
                folder.setEntityId(entityId);
                List<Folder> folders = folderMapper.getFolder(folder);
                if (folders == null || folders.isEmpty()) {
                    PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                    personalRecycleBin.setEntityId(entityId);
                    List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
                    if (personalRecycleBins != null && personalRecycleBins.size() == 1)
                        return personalRecycleBins.get(0).getEntityName();
                    else return null;
                } else {
                    folder = folders.get(0);
                }
                return folder.getEntityName();
            } else if (entityId.startsWith("file")) {
                File file = new File();
                file.setEntityId(entityId);
                List<File> files = fileMapper.getFile(file);
                if (files == null || files.isEmpty()) {
                    PersonalRecycleBin personalRecycleBin = new PersonalRecycleBin();
                    personalRecycleBin.setEntityId(entityId);
                    List<PersonalRecycleBin> personalRecycleBins = personalRecycleBinMapper.getPersonalRecycleBin(personalRecycleBin);
                    if (personalRecycleBins != null && personalRecycleBins.size() == 1)
                        return personalRecycleBins.get(0).getEntityName();
                    else return null;
                } else {
                    file = files.get(0);
                }
                return file.getEntityName();
            } else return null;
        }
    }

    @Override
    public Map<String, String> jsonObjectToStringMap(com.alibaba.fastjson.JSONObject jsonObject) {
        return jsonObject.toJavaObject(new com.alibaba.fastjson.TypeReference<Map<String, String>>(){});
    }

    @Override
    public String getEntityIdByPath(String roomId, String path) {
        String[] paths = path.split("/");
        String parentId = "root";
        for(String currentPath: paths) {
            Folder folder = new Folder();
            folder.setEntityRoom(roomId);
            folder.setEntityName(currentPath);
            folder.setParentId(parentId);
            System.out.println("folder: " + folder);
            List<Folder> folders = folderService.getFolder(folder);
            if(folders == null || folders.isEmpty()) {
                log.warn("未找到该路径的文件夹: {}", path);
                return null;
            }
            else if(folders.size() > 1){
                log.warn("该路径下文件夹不唯一: {}", path);
                return null;
            }
            parentId = folders.get(0).getEntityId();
        }
        return parentId;
    }
}